<html lang="zh-hans">
<head>
    <meta charset="utf-8"/>
    <meta name="author" content="FantasticMao"/>
    <title>当前天气预报</title>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-89151446-3"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-89151446-3');
    </script>
</head>

<body>
<h2 id="forecast"></h2>

<script src="../js/Data.js"></script>
<script>
    // override renderText 方法
    class DataZhHans extends Data {
        constructor(date, city,
                    weatherDesc, temp, humidity, pm25,
                    weatherDescFrom, weatherDescTo, maxTemp, minTemp, uvLevel, aqi, chanceOfRain) {
            super(date, city,
                weatherDesc, temp, humidity, pm25,
                weatherDescFrom, weatherDescTo, maxTemp, minTemp, uvLevel, aqi, chanceOfRain);
        }

        renderContent() {
            // 注意：「P M」中间得加个空格，不然 Siri 会念成「下午」
            let content = `${this.year} 年 ${this.month} 月 ${this.day} 日 ${this.city} 当前天气 ${this.weatherDesc}，气温 ${this.temp} 度，湿度百分之 ${this.humidity}，P M 二点五指数 ${this.pm25}。`;
            if (this.weatherDescFrom === this.weatherDescTo) {
                content = content + `预计今日天气 ${this.weatherDescFrom}，`;
            } else {
                content = content + `预计今日天气 ${this.weatherDescFrom} 到 ${this.weatherDescTo}，`;
            }
            content = content + `最高气温 ${this.maxTemp} 度，最低气温 ${this.minTemp} 度，紫外线强度 ${this.uvLevel}，空气质量 ${this.aqi}。`;
            return content;
        }
    }

    function parseData(json) {
        const date = new Date();
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        const dailyKeyFloat = (date.getTime() / (1000 * 60 * 60 * 24)) + 1;
        const dailyKey = parseInt(dailyKeyFloat.toString());

        const city = json['location']['city']; // 城市
        // 当前数据
        const weatherDesc = json['observe']['weatherText']; // 当前天气
        const temp = json['observe']['temperature']; // 当前温度
        const humidity = json['observe']['humidity'].replace('%', ''); // 当前湿度
        const pm25 = json['observe']['air']['pm25']; // 当前 pm2.5
        // 当日数据
        const weatherDescFrom = json['daily'][dailyKey]['weatherDescription'][0]; // 天气描述（开始）
        const weatherDescTo = json['daily'][dailyKey]['weatherDescription'][1]; // 天气描述（结束）
        const maxTemp = json['daily'][dailyKey]['temperature'][0]; // 最高气温
        const minTemp = json['daily'][dailyKey]['temperature'][1]; // 最低气温
        const uvLevel = json['daily'][dailyKey]['index']['list'][0]['level']; // 紫外线强度
        const aqi = json['daily'][dailyKey]['air']['aqic']; // 空气质量
        return new DataZhHans(date, city, weatherDesc, temp, humidity, pm25,
            weatherDescFrom, weatherDescTo, maxTemp, minTemp, uvLevel, aqi, null);
    }

    // 解析 URL 参数中的经度和纬度
    const params = new URL(window.location.href).searchParams;
    const lng = params.get('lng'); // 经度
    const lat = params.get('lat'); // 纬度

    if (lng === null) {
        throw new Error('illegal argument exception: lng 经度');
    } else if (lat === null) {
        throw new Error('illegal argument exception: lat 纬度');
    }

    (function () {
        const request = new XMLHttpRequest();
        request.open('GET',
            // 使用开源 CORS 代理服务，例如 https://github.com/Freeboard/thingproxy
            // `https://thingproxy.freeboard.io/fetch/https://mpv2.weather.com.cn/v2/?lng=${lng}&lat=${lat}`,
            // 使用 https://cors-proxy.fantasticmao.cn 代理服务，仅限 fantasticmao.github.com 和 fantasticmao.gitee.com 域名可用
            `https://cors-proxy.fantasticmao.cn/mpv2.weather.com.cn/v2/?lng=${lng}&lat=${lat}`,
            false);
        request.send(null);
        if (request.status === 200) {
            const json = JSON.parse(request.responseText);
            const data = parseData(json);
            document.getElementById('forecast').innerHTML = data.renderContent();
        } else {
            document.getElementById('forecast').innerHTML = "加载天气数据失败，请求失败";
        }
    })();
</script>
</body>
</html>
